const mqtt = require('mqtt')
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 9002 });

const client = mqtt.connect('mqtt://47.101.172.203:1883')
// 导入db模块
const db = require("./utils/db");
// 导入uuid
const uuid = require('uuid')
client.on('connect', function() {
    console.log('MQTT Connected')
    client.subscribe('BIRDS_GNSS1')
    client.subscribe('BIRDS_GNSS2')
    client.subscribe('BIRDS_GNSS3')
    client.subscribe('BIRDS_GNSS4')
    client.subscribe('BIRDS_GNSS5')
})

// 将MQTT消息事件处理函数移到这里
client.on('message', async function(topic, message) {
    console.log(`Received message from topic: ${topic}`);
    const tpMessage = JSON.parse(message.toString())
    tpMessage._topic = topic
    if(tpMessage.ID === 'GeoLocation') {
        const sql = 'insert into device_log (log_id, device_id, longitude, latitude, speed, altitude ) values (?, ?, ?, ?, ?, ?)'
        try {
            await db.query(sql, [uuid.v4(), topic, tpMessage.params.Longitude, tpMessage.params.Latitude, tpMessage.params.Speed, tpMessage.params.Altitude]);
        } catch(err) {
            console.log(err);
            try {
                const sql = 'insert into error_log (device_id, error_message ) values (?, ?)'
                await db.query(sql, [topic, JSON.stringify(err)]);
            } catch {}
        }
    } else if (tpMessage.ID === 'BATTERY') {
        const sql = 'insert into device_battery (log_id, device_id, volume, voltage ) values (?, ?, ?, ?)'
        try {
            await db.query(sql, [uuid.v4(), topic, tpMessage.params.volume, tpMessage.params.voltage]);
        } catch(err) {
            console.log(err);
            try {
                const sql = 'insert into error_log (device_id, error_message ) values (?, ?)'
                await db.query(sql, [topic, JSON.stringify(err)]);
            } catch {}
        }
    } else if (tpMessage.command) {
        const sql = 'insert into device_signal (log_id, device_id, command, json_data) values (?, ?, ?, ?)'
        try {
            await db.query(sql, [uuid.v4(), topic, tpMessage.command, JSON.stringify(tpMessage)]);
        } catch(err) {
            console.log(err);
            try {
                const sql = 'insert into error_log (device_id, error_message ) values (?, ?)'
                await db.query(sql, [topic, JSON.stringify(err)]);
            } catch {}
        }
    }
    // 广播消息到所有连接的WebSocket客户端
    wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(tpMessage));
        }
    });
});

// 监听WebSocket连接事件
wss.on('connection', (ws) => {
    ws.on('message', (webMessage) => {
        const data = webMessage.toJSON()
        const bufferData = Buffer.from(data.data)
        const jsonData = JSON.parse(bufferData)
        if(jsonData._params && jsonData._topic) {
            client.publish(jsonData._topic, JSON.stringify(jsonData._params))
        }
    });

    ws.on('close', () => {
        console.log('WebSocket Connection closed');
    });
});
